package com.yksj.healthtalk.ui.salon;

import java.util.ArrayList;

import org.handmark.pulltorefresh.library.PullToRefreshBase;
import org.handmark.pulltorefresh.library.PullToRefreshBase.OnRefreshListener2;
import org.handmark.pulltorefresh.library.PullToRefreshListView;
import org.staggered.lib.internal.StaggerAdapterView;
import org.staggered.lib.internal.StaggerAdapterView.OnItemClickListener;

import sfs2x.client.core.SFSEvent;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.os.Handler;
import android.support.v4.app.DialogFragment;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.CheckBox;
import android.widget.ListView;

import com.yksj.healthtalk.adapter.SalonAdapter;
import com.yksj.healthtalk.adapter.SalonAdapter.onClickSalonAttentionListener;
import com.yksj.healthtalk.adapter.SalonAdapter.onClickSalonHeadListener;
import com.yksj.healthtalk.comm.DoubleBtnFragmentDialog;
import com.yksj.healthtalk.comm.LodingFragmentDialog;
import com.yksj.healthtalk.comm.RootFragment;
import com.yksj.healthtalk.comm.DoubleBtnFragmentDialog.OnDilaogClickListener;
import com.yksj.healthtalk.db.ChatUserHelper;
import com.yksj.healthtalk.entity.GroupInfoEntity;
import com.yksj.healthtalk.net.http.ObjectHttpResponseHandler;
import com.yksj.healthtalk.net.socket.SmartFoxClient;
import com.yksj.healthtalk.services.CoreService;
import com.yksj.healthtalk.services.MessagePushService;
import com.yksj.healthtalk.ui.R;
import com.yksj.healthtalk.ui.app.AppData;
import com.yksj.healthtalk.ui.app.HTalkApplication;
import com.yksj.healthtalk.ui.chatting.ChatActivity;
import com.yksj.healthtalk.ui.salon.SalonSelectPaymentOptionActivity.OnBuyTicketHandlerListener;
import com.yksj.healthtalk.utils.SalonHttpUtil;
import com.yksj.healthtalk.utils.SharePreUtils;
import com.yksj.healthtalk.utils.SystemUtils;
import com.yksj.healthtalk.utils.ToastUtil;

/**
 * @ClassName: SalonCollectionActivity
 * @Description: 话题首页
 * @author wangtao wt0710910108_gmail_com
 * @date 2012-12-31 上午9:56:30
 */
public class SalonCollectionMainFragment extends RootFragment implements
		OnClickListener, onClickSalonHeadListener,
		onClickSalonAttentionListener, OnItemClickListener,
		OnRefreshListener2<ListView>,
		android.widget.AdapterView.OnItemClickListener,
		OnBuyTicketHandlerListener {

	private int sort = 0;// 排序类型 最新 最热...
	private ArrayList<GroupInfoEntity> salonEntities;// 话题数据
	private SalonAdapter mSalonAdapter;
	private ListView salonListView;
	private PullToRefreshListView pullRefreshView;
	private GroupInfoEntity cacheGroupInfoEntity;
	private String Flag;
	private String flagPlacing;
	private GroupInfoEntity mGroupInfoEntity;
	IntentFilter filter;
	AppData mAppData;
	private ChatUserHelper chatUserHelper;
	private CheckBox hotestCheckBox;
	private CheckBox newestCheckBox;
	private CheckBox allCheckBox;
	private CheckBox isCheckedBox;// 现在选中的条目
	private int CHATTINGCODE = 2;
	BroadcastReceiver receiver = new BroadcastReceiver() {

		@Override
		public void onReceive(Context context, Intent intent) {
			// TODO Auto-generated method stub
			String action = intent.getAction();
			if (action.equals(MessagePushService.ACTION_COLLECT_GROUP_NOT)) {
				LodingFragmentDialog.dismiss(getFragmentManager());
				String result = intent.getStringExtra("result");
				if (result.equals("0")) {
					ToastUtil.showShort(getActivity(), R.string.groupNewFail);
				} else {
					SalonHttpUtil.requestUnfollowToSalonResult(getActivity(),cacheGroupInfoEntity, mAppData, chatUserHelper);
					mSalonAdapter.notifyDataSetChanged();
				}
			} else if (action.equals(MessagePushService.ACTION_COLLECT_GROUP)) {
				LodingFragmentDialog.dismiss(getFragmentManager());
				String result = intent.getStringExtra("result");
				if (result.equals("0")) {
					ToastUtil.showShort(getActivity(), R.string.groupNewFail);
				} else {
					SalonHttpUtil.requestAttentionToSalonResult(getActivity(),cacheGroupInfoEntity, mAppData, chatUserHelper);
					mSalonAdapter.notifyDataSetChanged();
				}
			} else if (action.equals(SFSEvent.CONNECTION_LOST)) {
				LodingFragmentDialog.dismiss(getFragmentManager());
			} else if (action.equals(CoreService.ACTION_MESSAGE)) {
				if (intent.hasExtra("senderId")) {
					mSalonAdapter.notifyDataSetChanged();
				}

			}else  if(CoreService.ACTION_COMMONT_CONTENT.equals(intent.getAction())){
				DoubleBtnFragmentDialog.showDefault(getChildFragmentManager(),"亲，您的好评是对我们最大的鼓励~", "下次吧", "鼓励一下",new OnDilaogClickListener() {
					@Override
					public void onDismiss(DialogFragment fragment) {
						SharePreUtils.updateCommentGood();
					}
					@Override
					public void onClick(DialogFragment fragment, View v) {
						SharePreUtils.updateCommentGoodDay();
						SystemUtils.commentGood(getActivity());
					}
				});
			}
		}

	};
	
	Handler handler = new Handler();
	private String groupName;//从主页的搜索跳转  传参

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		groupName = getArguments().getString("groupName");
		chatUserHelper = ChatUserHelper.getInstance();
	}
	
	
	// 注册广播
	@Override
	public void onStart() {
		filter = new IntentFilter();
		// 取消关注的过滤器
		filter.addAction(MessagePushService.ACTION_COLLECT_GROUP_NOT);
		filter.addAction(MessagePushService.ACTION_MESSAGE);
		filter.addAction(MessagePushService.ACTION_COLLECT_GROUP);
		filter.addAction(CoreService.ACTION_COMMONT_CONTENT);
		filter.addAction(SFSEvent.CONNECTION_LOST);
		getActivity().registerReceiver(receiver, filter);
		super.onStart();
	}

	@Override
	public void onStop() {
		getActivity().unregisterReceiver(receiver);
		super.onStop();
	}

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		mAppData = HTalkApplication.getAppData();
		View view = inflater.inflate(R.layout.salon_collection_layout,
				container, false);
		initUI(view);
		initData(view);

		if (!TextUtils.isEmpty(groupName)) {//主页搜索
			mGroupInfoEntity = new GroupInfoEntity();
			mGroupInfoEntity.setName(groupName);
			checkId(allCheckBox);
			getSalons(isCheckedBox);
		}else {
			getSalons(hotestCheckBox);
		}
	
		return view;
	}

	@SuppressLint("ResourceAsColor")
	@Override
	public void onClick(View v) {
		Intent intent = null;
		switch (v.getId()) {
		case R.id.title_right2:
			intent = new Intent(getActivity(), SalonNewActivity.class);
			startActivityForResult(intent, 0);
			break;
		case R.id.title_back:
			// getActivity().finish();
			onBackPressed(v);
			break;
		case R.id.title_right:
			intent = new Intent();
			intent.setClass(getActivity(), SalonSearchMainActivity.class);
			intent.putExtra("mGroupInfoEntity", mGroupInfoEntity);
			startActivityForResult(intent, 0);
			break;
		case R.id.hotest_rb:
		case R.id.newest_rb:
		case R.id.all_rb:
			getSalons(v);
			break;

		}
	}

	/**
	 * 获取话题
	 * 
	 * @param v
	 */
	private void getSalons(View v) {
		Flag = "";
		flagPlacing = "-100000";
		if (mGroupInfoEntity == null) {
			mGroupInfoEntity = new GroupInfoEntity();
		}
		mGroupInfoEntity.setFlag(Flag);
		mGroupInfoEntity.setFlagPlacing(flagPlacing);
		mGroupInfoEntity.setPagesize(1);
		mGroupInfoEntity.setType(1);
		mGroupInfoEntity.setCreateCustomerID(SmartFoxClient.getLoginUserId());
		salonEntities.clear();
		mSalonAdapter.notifyDataSetChanged();
		pullRefreshView.setRefreshing();
		switch (v.getId()) {
		case R.id.all_rb:
			sort = 0;
			break;
		case R.id.newest_rb:
			sort = 1;
			break;
		case R.id.hotest_rb:
			sort = 2;
			break;
		default:
			break;
		}
		checkId((CheckBox) v);
		if (SmartFoxClient.getLoginUserId() != null) {
//			SalonHttpUtil.getSalonInfo(mGroupInfoEntity, sort, this);
			SalonHttpUtil.getSalonInfoData(mGroupInfoEntity, sort,responseHandler);
		} else {
			ToastUtil.showShort(getActivity(), "你还没有登录");
		}
	}

	/**
	 * 初始化页面
	 */
	private void initUI(View v) {
		initTitleView(v);
		// 初始化空间对象
		pullRefreshView = (PullToRefreshListView) v.findViewById(R.id.hall);
		hotestCheckBox = (CheckBox) v.findViewById(R.id.hotest_rb);
		newestCheckBox = (CheckBox) v.findViewById(R.id.newest_rb);
		allCheckBox = (CheckBox) v.findViewById(R.id.all_rb);
		v.findViewById(R.id.top_line).setVisibility(View.GONE);
		// 设置监听事件
		titleLeftBtn.setOnClickListener(this);
		titleRightBtn.setOnClickListener(this);
		titleRightBtn2.setOnClickListener(this);
		newestCheckBox.setOnClickListener(this);
		hotestCheckBox.setOnClickListener(this);
		allCheckBox.setOnClickListener(this);

		titleRightBtn.setVisibility(View.VISIBLE);
		titleRightBtn2.setVisibility(View.VISIBLE);
		titleRightBtn.setBackgroundResource(R.drawable.icon_search_press);
		titleRightBtn2.setBackgroundResource(R.drawable.icon_create);

	}

	/**
	 * 初始化数据
	 */
	private void initData(View v) {
		mGroupInfoEntity = new GroupInfoEntity();
		salonListView = pullRefreshView.getRefreshableView();
		pullRefreshView.setOnRefreshListener(this);
		salonListView.setOnItemClickListener(this);
		salonEntities = new ArrayList<GroupInfoEntity>();
		// 设置列表
		mSalonAdapter = new SalonAdapter(getActivity(), salonEntities);
		mSalonAdapter.setonClickSalonHeadListener(this);
		mSalonAdapter.setonClickSalonAttentionListener(this);
		salonListView.setAdapter(mSalonAdapter);
		titleTextV.setText("话题");
	}



	// 话题头像的点击事件
	@Override
	public void onSalonHeadClick(View v, GroupInfoEntity entity, int position) {
		if (entity.getCreateCustomerID().equals(
				SmartFoxClient.getLoginUserId())) {
			Intent intent = new Intent();
			intent.setClass(getActivity(), SalonReadSelf.class);
			intent.putExtra("id", entity.getId());
			startActivity(intent);
		} else {
			Intent intent = new Intent();
			intent.setClass(getActivity(), SalonInformationActivity.class);
			Bundle bundle = new Bundle();
			intent.putExtra("id", entity.getId());
			bundle.putInt("position", position);
			intent.putExtras(bundle);
			startActivityForResult(intent, 0);
		}
	}

	@Override
	public void onSalonAttentionClick(View v, GroupInfoEntity mSalonName,
			int positon) {
		cacheGroupInfoEntity = SalonHttpUtil.requestAttOrUnfollowToSalon(
				getActivity(),
				mSalonName);
	}

	@Override
	public void onItemClick(AdapterView<?> parent, View view, int position,
			long id) {
		try {
			SalonHttpUtil.onItemClick(getActivity(), this,getChildFragmentManager(), salonEntities.get(position - 1),true);
		} catch (Exception e) {
		}
	}

	@Override
	public void onActivityResult(int requestCode, int resultCode, Intent data) {
		super.onActivityResult(requestCode, resultCode, data);
		if(data==null)return;
		switch (requestCode) {
		case 0:
			flagPlacing = "-100000";
			Flag = "";
			if (data.hasExtra("positions")) {
				ArrayList<String> list = (ArrayList<String>) data.getExtras().get("positions");
				mGroupInfoEntity = (GroupInfoEntity) data.getExtras().get(
						"mGroupInfoEntity");
				String dataClickId = (String) data.getExtras().get("dataClickId");
				// 不是从搜索首页全部搜索
				if (!dataClickId.equals("0")) {
					mGroupInfoEntity.setFlag(Flag);
					mGroupInfoEntity.setFlagPlacing(flagPlacing);
					mGroupInfoEntity.setType(1);
					mGroupInfoEntity.setUpperId(dataClickId);
					StringBuilder builder = new StringBuilder();
					for (int i = 0; i < list.size(); i++) {
						builder.append(Integer.valueOf(list.get(i)));
						builder.append(",");
					}
					builder.deleteCharAt(builder.toString().length() - 1);
					mGroupInfoEntity.setInfoId(builder.toString());
				} else {
					mGroupInfoEntity.setFlag(Flag);
					mGroupInfoEntity.setFlagPlacing(flagPlacing);
					mGroupInfoEntity.setType(1);
					mGroupInfoEntity.setUpperId(dataClickId);
					mGroupInfoEntity.setInfoId("0");
					
				}
				checkId(allCheckBox);
				getSalons(isCheckedBox);
			}
		
			break;
		case 1000:
			if (data != null && data.hasExtra("mSalonInformationEntity")) {
				// 从话题信息加关注和取消关注里面返回
				if ((Integer) data.getExtras().get("position") != -1) {
					GroupInfoEntity entity = (GroupInfoEntity) data.getExtras().get("mSalonInformationEntity");
					salonEntities.set((Integer) data.getExtras().get("position"),entity);
					mSalonAdapter.notifyDataSetChanged();
				}
				return;
			}
			break;
			
		}
		
	}

	@Override
	public void onPullDownToRefresh(PullToRefreshBase<ListView> refreshView) {
		Flag = "";
		flagPlacing = "-100000";
		mGroupInfoEntity = new GroupInfoEntity();
		mGroupInfoEntity.setFlag(Flag);
		mGroupInfoEntity.setFlagPlacing(flagPlacing);
		mGroupInfoEntity.setPagesize(1);
		mGroupInfoEntity.setType(1);
		mGroupInfoEntity.setCreateCustomerID(SmartFoxClient.getLoginUserId());
		SalonHttpUtil.getSalonInfoData(mGroupInfoEntity, sort,responseHandler);
	}

	@Override
	public void onDestroyView() {
		super.onDestroyView();
	}

	@Override
	public void onPullUpToRefresh(PullToRefreshBase<ListView> refreshView) {
		mGroupInfoEntity.setFlag(Flag);
		mGroupInfoEntity.setFlagPlacing(flagPlacing);
		SalonHttpUtil.getSalonInfoData(mGroupInfoEntity, sort,responseHandler);
	}
	
	ResponseHandler responseHandler=new ResponseHandler(sort);
	
	class ResponseHandler extends ObjectHttpResponseHandler{
		int sortNum ;
		public ResponseHandler(int sort) {
			this.sortNum=sort;
		}
		
		public void onFinish() {
			super.onFinish();
			pullRefreshView.onRefreshComplete();
		};
		
		@Override
		public void onSuccess(Object response) {
			super.onSuccess(response);
			if(response==null)return;
			if (flagPlacing.equals("-100000")) {
				salonEntities.clear();
			}
			 ArrayList<GroupInfoEntity> entities=(ArrayList<GroupInfoEntity>) response;
			 if(entities.size()==0){
				 ToastUtil.showToastPanl("暂无更多内容...");
				 return;
			 }
				salonEntities.addAll(entities);
				// //点击按钮重新刷新adapter并且指定第一个开始
				mSalonAdapter.notifyDataSetChanged();
				Flag = mSalonAdapter.getPageFlagMark(false);
				flagPlacing = mSalonAdapter.getFlagPlacingMark(false);
				if (flagPlacing.equals("-100000")) {
					salonListView.setSelection(0);
				}
		}
		
		@Override
		public Object onParseResponse(String content) {
			if (!content.equals("N")) {
				return  SalonHttpUtil.jsonAnalysisSalonEntity(getActivity(),content);
			}else {
				return null;
			}
		}
	}
	
	
	
	@Override
	public void onItemClick(StaggerAdapterView<?> parent, View view,
			int position, long id) {
	}

	@Override
	public void onTicketHandler(String state, GroupInfoEntity entity) {
		// TODO Auto-generated method stub
		if ("0".equals(state)) {
		} else if ("-1".equals(state)) {
			ToastUtil.showShort(getActivity(), "服务器出错");
		} else {
			Intent intent1 = new Intent();
			intent1.putExtra(ChatActivity.KEY_PARAME, entity);
			intent1.setClass(getActivity(), ChatActivity.class);
			startActivityForResult(intent1, CHATTINGCODE);
		}
	}

	/**
	 * 点击按钮
	 * 
	 * @param box
	 */
	void checkId(CheckBox box) {
		hotestCheckBox.setChecked(false);
		newestCheckBox.setChecked(false);
		allCheckBox.setChecked(false);
		box.setChecked(true);
		isCheckedBox = box;
		allCheckBox.setTextColor(getResources().getColor(R.color.tab_txt_gray));
		newestCheckBox.setTextColor(getResources().getColor(
				R.color.tab_txt_gray));
		hotestCheckBox.setTextColor(getResources().getColor(
				R.color.tab_txt_gray));
		box.setTextColor(getResources().getColor(R.color.tab_txt_orange));
	}
}
